package org.gene.aop;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class MethodTimeAdvice implements MethodAdvice{
	private static final Logger Log = Logger.getLogger(MethodTimeAdvice.class); 
	
	public void pointcut(){}
	
	String strLog = null;
	
	public void doBefore (JoinPoint jp){
		strLog = "log Begining method: "  
                + jp.getTarget().getClass().getName() + "."  
                + jp.getSignature().getName();   
		Log.info(strLog);  
	   }

	@Override
   public void doAfter(JoinPoint jp){
		strLog = "log Ending method: "  
                + jp.getTarget().getClass().getName() + "."  
                + jp.getSignature().getName();
		 Log.info(strLog);  

   }

	@Override
   public Object doAround(ProceedingJoinPoint pjp)throws Throwable{
		StopWatch clock = new StopWatch(); 
		clock.start();
        Object retVal = pjp.proceed();  
        clock.stop();
     // 方法参数类型，转换成简单类型 
        Object[] args = pjp.getArgs();
        /*Method method =  pjp.getTarget().getClass().getMethod(pjp.getSignature().getName());
        Class[] params = method.getParameterTypes();
        
        String[] simpleParams = new String[params.length]; 
        for(int i=0;i<params.length;i++){
        	Log.info(params[i].getName());
        	simpleParams[i] = params[i].getSimpleName();
        }*/
        Log.info("Taks:"+clock.getTime()+" ms ["
        		+pjp.getTarget().getClass().getName()+"."+pjp.getSignature().getName()+"][args:"
        		+StringUtils.join(args,",")
        		+"]");
        return retVal;
   }
	
	@Override
	public void afterThrowing(Exception ex){
		Log.info("==============Exception Message==============");
		Log.info(ex);
		Log.info("==============Exception Message==============");
	}
}
